package com.woniuxy.classteacher.service.impl;

import com.woniuxy.classteacher.mapper.*;
import com.woniuxy.classteacher.service.ClassScoreService;
import com.woniuxy.commons.entity.AnswerSheet;
import com.woniuxy.commons.entity.StudentInfo;
import com.woniuxy.commons.entity.wyh.TeacherInfo;
import com.woniuxy.commons.entity.wyh.TeamInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author 李英勇
 * @date 2020/7/23 - 17:24
 */
@Service
public class ClassScoreServiceImpl implements ClassScoreService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ChangeClassMapper changeClassMapper;
    @Autowired
    private AnswerSheetMapper answerSheetMapper;
    @Autowired
    private ClassTeacherMapper classTeacherMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @Author: 李英勇
     * @Description: 增加差生进入差生池
     * @DateTime: 2020/8/5 16:33
     * @Params: [refreshToken]
     * @Return void
     */
    @Override
    @Transactional
    public void addBadStuPool(String refreshToken) {
        //在redis中获取用户的role和rid
        //通过refreshToken获取数据
        Map<Object, Object> data = redisTemplate.opsForHash().entries(refreshToken);
        //获取role
        String role = (String) data.get("role");
        //获取rid
        int rid = (int) data.get("rid");
        //通过rid获取老师信息
        TeacherInfo teacherInfo = classTeacherMapper.findTeacherInfoByTcid(rid);
        //学校名称
        String sname = teacherInfo.getSchoolInfo().getSname();

        //排序list
        List<AnswerSheet> sortList = new ArrayList<>();
        //存放差生的list
        List<StudentInfo> badList = new ArrayList<>();

        if ("teacher".equals(role)) {
            //通过rid查询班主任id
            List<Integer> tmids = changeClassMapper.findTmIdByTeacherId(rid);
            if (tmids.size() != 0) {
                //通过tmids查询所管的所有班级
                List<TeamInfo> teamInfos = classMapper.findTeamInfoByTmId(tmids);
                //遍历班级分别查出每个班的学生
                for (int i = 0; i < teamInfos.size(); i++) {
                    //班级id
                    Integer teId = teamInfos.get(i).getTeId();
                    //班级名称
                    String tname = teamInfos.get(i).getTname();
                    //班级学生
                    List<StudentInfo> stus = studentMapper.findStusByClassid(teId);
                    //班级总人数
                    Integer tnumber = teamInfos.get(i).getTnumber();
                    //计算班级20%
                    double num = Math.ceil(tnumber * 0.2);

                    //通过班级id查询班级
                    TeamInfo teamInfoByTeid = classMapper.findTeamInfoByTeid(teId);
                    //获取年级名称
                    String gradeType = teamInfoByTeid.getGradeInfo().getGradeType();


                    for (int j = 0; j < stus.size(); j++) {
                        StudentInfo stu = stus.get(j);
                        //这个学生的所有成绩总分
                        AnswerSheet total = answerSheetMapper.findTotalScoreBySid(stu.getStuid());
                        sortList.add(total);
                    }
                    //排序
                    sortList.sort(new Comparator<AnswerSheet>() {
                        @Override
                        public int compare(AnswerSheet o1, AnswerSheet o2) {
                            return (int) (o2.getSheetScore() - o1.getSheetScore());
                        }
                    });
                    System.out.println("===============================" + sortList);
                    for (int k = 0; k < sortList.size() - num; k++) {
                        //获取非差生的信息
                        int s = (int) (sortList.get(k).getSheetStudentNo());
                        StudentInfo stuByStuid = studentMapper.findStuByStuid(s);
                        System.out.println("================" + stuByStuid);
                        //判断非差生的差生计数是否为零
                        if (stuByStuid.getBadstudent() != 0) {
                            //差生次数-2
                            studentMapper.reduceCountByStuid(stuByStuid.getStuid());
                        }
                    }

                    for (int m = sortList.size() - 1; m >= sortList.size() - num; m--) {
                        //获取差生的信息
                        int s = (int) (sortList.get(m).getSheetStudentNo());
                        //差生次数+1
                        studentMapper.addBadCountByStuid(s);
                        System.out.println("============");
                    }

                    //重新获取学生
                    stus = studentMapper.findStusByClassid(teId);
                    //遍历所有的学生，差生计数大于等于5的放入list
                    for (int n = 0; n < stus.size(); n++) {
                        //获取学生的信息
                        Integer s = stus.get(n).getStuid();
                        StudentInfo stuByStuid = studentMapper.findStuByStuid(s);
                        //判断差生计数是否大于等于5
                        if (stuByStuid.getBadstudent() >= 5) {
                            //放入list
                            badList.add(stuByStuid);
                        }
                    }

                    //判断redis中是否存在这个班的差生池
                    Map<Object, Object> school = redisTemplate.opsForHash().entries(sname);
                    System.out.println("=================" + school);
                    if (school.isEmpty()) {
                        Map<String, Object> grade1 = new HashMap<>();
                        Map<String, Object> class1 = new HashMap<>();
                        class1.put(tname, badList);
                        grade1.put(gradeType, class1);
                        redisTemplate.opsForHash().putAll(sname, grade1);
                    } else {
                        //从redis中拿出这个班的差生
                        Map<String, Object> clazz = (Map<String, Object>) school.get(gradeType);
                        List<StudentInfo> stus1 = (List<StudentInfo>) clazz.get(tname);
                        System.out.println("=================" + stus1);


                        //将新的差生池放入redis
                        clazz.put(tname, badList);
                        redisTemplate.opsForHash().put(sname, gradeType, clazz);

                        //取差集
                        badList.removeAll(stus1);
                        System.out.println("=================" + badList);

                        //异步发送消息给任课老师重点关注
                        if ("高一".equals(gradeType) && "一班".equals(tname)) {
                            rabbitTemplate.convertAndSend("directExchange", "高一一班", badList);
                        } else if ("高二".equals(gradeType) && "一班".equals(tname)) {
                            rabbitTemplate.convertAndSend("directExchange", "高二一班", badList);
                        } else if ("高三".equals(gradeType) && "一班".equals(tname)) {
                            rabbitTemplate.convertAndSend("directExchange", "高三一班", badList);
                        }

                        System.out.println("本次考试新增差生" + badList);


                    }


                }
            }
        }


        //redis数据结构
        //学校：{
        //  年级1：{
        //      班级1：{
        //          学生1id
        //          学生2id
        //      }
        //      班级2: {
        //          学生1id
        //          学生2id
        //      }
        //  }
        //  年级2：{
        //      班级1：{
        //          学生1id
        //          学生2id
        //         }
        //      班级2: {
        //         学生1id
        //         学生2id
        //      }
        //  }
        // }
    }


}
